package com.wenzhoujie;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.wenzhoujie.library.title.SDTitleTwoRightButton.SDTitleTwoRightButtonListener;
import com.wenzhoujie.library.utils.SDToast;
import com.wenzhoujie.library.utils.SDViewUtil;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lingou.www.R;
import com.lingou.www.R.color;
import com.sunday.eventbus.SDBaseEvent;
import com.wenzhoujie.adapter.CategoryCateLeftAdapter;
import com.wenzhoujie.adapter.CategoryCateRightAdapter;
import com.wenzhoujie.adapter.CategoryOrderAdapter;
import com.wenzhoujie.adapter.CategoryQuanLeftAdapterNew;
import com.wenzhoujie.adapter.CategoryQuanRightAdapterNew;
import com.wenzhoujie.adapter.YouHuiListAdapter;
import com.wenzhoujie.app.AppHelper;
import com.wenzhoujie.baidumap.BaiduMapManager;
import com.wenzhoujie.constant.Constant;
import com.wenzhoujie.constant.Constant.CategoryOrderTypeName;
import com.wenzhoujie.constant.Constant.CategoryOrderTypeValue;
import com.wenzhoujie.constant.Constant.SearchTypeMap;
import com.wenzhoujie.constant.Constant.SearchTypeNormal;
import com.wenzhoujie.constant.Constant.TitleType;
import com.wenzhoujie.customview.SD2LvCategoryView;
import com.wenzhoujie.customview.SDBottomNavigatorBaseItem;
import com.wenzhoujie.customview.SDLvCategoryView;
import com.wenzhoujie.customview.SDLvCategoryView.SDLvCategoryViewListener;
import com.wenzhoujie.event.EnumEventTag;
import com.wenzhoujie.fragment.HomeRecommendSupplierFragment;
import com.wenzhoujie.fragment.NearByVoucherFragment;
import com.wenzhoujie.http.InterfaceServer;
import com.wenzhoujie.model.Bcate_listBcate_typeModel;
import com.wenzhoujie.model.Bcate_listModel;
import com.wenzhoujie.model.CategoryOrderModel;
import com.wenzhoujie.model.Quan_listModel;
import com.wenzhoujie.model.Quan_listQuan_subModel;
import com.wenzhoujie.model.RequestModel;
import com.wenzhoujie.model.YouhuilistItemModel;
import com.wenzhoujie.model.act.YouhuilistActModel;
import com.wenzhoujie.utils.IocUtil;
import com.wenzhoujie.utils.JsonUtil;
import com.wenzhoujie.utils.SDInterfaceUtil;
import com.wenzhoujie.utils.SDViewNavigatorManager;
import com.wenzhoujie.utils.ViewInject;
import com.wenzhoujie.work.AppRuntimeWorker;

/**
 * 优惠列表界面
 * 
 * @author js02
 * 
 */
public class YouHuiListActivity extends BaseActivity implements OnClickListener
{

	/** 关键字 */
	public static final String EXTRA_KEY_WORD = "extra_key_word";

	/** 大分类id */
	public static final String EXTRA_CATE_ID = "extra_cate_id";

	/** 小分类id */
	public static final String EXTRA_CATE_TYPE_ID = "extra_cate_type_id";

	@ViewInject(id = R.id.act_youhui_list_cv_left)
	private SD2LvCategoryView mCvLeft = null;

	@ViewInject(id = R.id.act_youhui_list_cv_middle)
	private SD2LvCategoryView mCvMiddle = null;

	@ViewInject(id = R.id.act_youhui_list_cv_right)
	private SDLvCategoryView mCvRight = null;

	@ViewInject(id = R.id.act_youhui_list_ll_empty)
	private LinearLayout mLlEmpty = null;

	@ViewInject(id = R.id.act_youhui_list_ll_current_location)
	private LinearLayout mLlCurrentLocation = null;

	@ViewInject(id = R.id.act_youhui_list_tv_current_address)
	private TextView mTvAddress = null;

	@ViewInject(id = R.id.act_youhui_list_tv_location)
	private ImageView mIvLocation = null;

	@ViewInject(id = R.id.act_youhui_list_ll_current_search)
	private LinearLayout mLlCurrentSearch = null;

	@ViewInject(id = R.id.act_youhui_list_tv_current_keyword)
	private TextView mTvCurrentKeyword = null;

	@ViewInject(id = R.id.act_youhui_list_ptrlv_content)
	private PullToRefreshListView mPtrlvContent = null;
	
	@ViewInject(id=R.id.frag_fl_youhui)
	private FrameLayout mFLfrag_fl_youhui;
	
	@ViewInject(id=R.id.btn_youhuquan)
	private Button mBtnYouhuiquan;
	
	@ViewInject(id=R.id.btn_daijinquan)
	private Button mBtnDaijinquan;
	
	@ViewInject(id=R.id.iv_daijinquan)
	private ImageView mIv_daijinquan;
	
	@ViewInject(id=R.id.iv_youhuiquan)
	private ImageView mIv_youhuiquan;

	private YouHuiListAdapter mAdapter = null;
	private List<YouhuilistItemModel> mListModel = new ArrayList<YouhuilistItemModel>();
	private SDViewNavigatorManager mViewManager = new SDViewNavigatorManager();

	private boolean isFirstBindCategoryViewData = true;

	private int pageTotal;
	// ====================提交服务端参数
	private String city_id;
	private String quan_id;
	private String cate_id;
	private String keyword;
	private String city_name;
	private String order_type;
	private String latitude_top;
	private String latitude_bottom;
	private String longitude_left;
	private String longitude_right;
	private String m_distance;
	private int page;
	private String merchant_id;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setmTitleType(TitleType.TITLE_TWO_RIGHT_BUTTON);
		setContentView(R.layout.act_youhui_list);
		IocUtil.initInjectedView(this);
		init();
	}

	private void init()
	{
		initTitle();
		getIntentData();
		bindDefaultLvData();
		initCategoryView();
		initCategoryViewNavigatorManager();
		registeClick();
		initPullRefreshLv();
	}

	private void initTitle()
	{
		mTitleTwoRightBtns.setmListener(new SDTitleTwoRightButtonListener()
		{

			@Override
			public void onRightButton2CLick_SDTitleTwoRightButton(View v)
			{
				Intent intent = new Intent(YouHuiListActivity.this, HomeSearchActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				intent.putExtra(HomeSearchActivity.EXTRA_SEARCH_TYPE, SearchTypeNormal.YOU_HUI);
				startActivity(intent);
			}

			@Override
			public void onRightButton1CLick_SDTitleTwoRightButton(View v)
			{
				Intent intent = new Intent(YouHuiListActivity.this, MapSearchActivity.class);
				intent.putExtra(MapSearchActivity.EXTRA_SEARCH_TYPE, SearchTypeMap.YOU_HUI);
				startActivity(intent);
			}

			@Override
			public void onLeftButtonCLick_SDTitleTwoRightButton(View v)
			{
				finish();
			}
		});

		mTitleTwoRightBtns.setTitleTop("优惠券列表");

		mTitleTwoRightBtns.setRightImage1(R.drawable.ic_location_home_top);
		mTitleTwoRightBtns.setRightImage2(R.drawable.ic_search_home_top);
	}

	/**
	 * 从intent获取数据
	 */
	private void getIntentData()
	{
		Intent intent = getIntent();
		cate_id = intent.getStringExtra(EXTRA_CATE_ID);
		keyword = intent.getStringExtra(EXTRA_KEY_WORD);

		if (TextUtils.isEmpty(keyword))
		{
			//mLlCurrentLocation.setVisibility(View.VISIBLE);
			mLlCurrentLocation.setVisibility(View.GONE);
			mLlCurrentSearch.setVisibility(View.GONE);
			if (BaiduMapManager.getInstance().getCurAddress() != null)
			{
				mTvAddress.setText(BaiduMapManager.getInstance().getCurAddressShort());
			}
		} else
		{
			mLlCurrentLocation.setVisibility(View.GONE);
			//mLlCurrentSearch.setVisibility(View.VISIBLE);
			mLlCurrentSearch.setVisibility(View.GONE);
			mTvCurrentKeyword.setText(keyword);
		}
	}

	/**
	 * 初始化下拉刷新控件
	 */
	private void initPullRefreshLv()
	{
		mPtrlvContent.setMode(Mode.BOTH);
		mPtrlvContent.setOnRefreshListener(new OnRefreshListener2<ListView>()
		{

			@Override
			public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView)
			{
				page = 1;
				requestData(false);
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView)
			{
				page++;
				if (page > pageTotal && pageTotal > 0)
				{
					SDToast.showToast("没有更多数据了");
					mPtrlvContent.onRefreshComplete();
				} else
				{
					requestData(true);
				}
			}
		});

		mPtrlvContent.setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id)
			{
				YouhuilistItemModel goodsModel = mAdapter.getItem((int) id);
				if (goodsModel != null && goodsModel.getId() != null)
				{
					Intent intent = new Intent(getApplicationContext(), YouHuiDetailActivity.class);
					intent.putExtra(YouHuiDetailActivity.EXTRA_YOUHUI_ID, goodsModel.getId());
					startActivity(intent);
				}

			}
		});

		mPtrlvContent.setRefreshing();
		
		NearByVoucherFragment mFragRecommendSupplier = new NearByVoucherFragment();
		replaceFragment(mFragRecommendSupplier, R.id.frag_fl_youhui);
	}

	private void bindDefaultLvData()
	{
		mAdapter = new YouHuiListAdapter(mListModel, YouHuiListActivity.this);
		mPtrlvContent.setAdapter(mAdapter);
	}

	private void initCategoryViewNavigatorManager()
	{
		SDBottomNavigatorBaseItem[] items = new SDBottomNavigatorBaseItem[] { mCvLeft, mCvMiddle, mCvRight };
		mViewManager.setItems(items);
		mViewManager.setmMode(SDViewNavigatorManager.Mode.CAN_NONE_SELECT);
	}

	private void initCategoryView()
	{

		mCvLeft.setmBackgroundNormal(R.drawable.bg_choosebar_press_down);
		mCvLeft.setmBackgroundSelect(R.drawable.bg_choosebar_press_up);
		mCvLeft.setmTextColorNormal(getResources().getColor(color.text_home_item_content));
		mCvLeft.setmTextColorSelect(getResources().getColor(color.main_color));
		mCvLeft.setmListener(new SD2LvCategoryView.SD2LvCategoryViewListener()
		{

			@Override
			public void onRightItemSelect(int leftIndex, int rightIndex, Object leftModel, Object rightModel)
			{
				Bcate_listModel left = (Bcate_listModel) leftModel;
				cate_id = left.getId();
				mPtrlvContent.setRefreshing();
			}

			@Override
			public void onLeftItemSelect(int leftIndex, Object leftModel, boolean isNotifyDirect)
			{
				if (isNotifyDirect)
				{
					Bcate_listModel left = (Bcate_listModel) leftModel;
					cate_id = left.getId();
					mPtrlvContent.setRefreshing();
				}
			}
		});

		mCvMiddle.setmBackgroundNormal(R.drawable.bg_choosebar_press_down_2);
		mCvMiddle.setmBackgroundSelect(R.drawable.bg_choosebar_press_up_2);
		mCvMiddle.setmTextColorNormal(getResources().getColor(color.text_home_item_content));
		mCvMiddle.setmTextColorSelect(getResources().getColor(color.main_color));
		mCvMiddle.setmListener(new SD2LvCategoryView.SD2LvCategoryViewListener()
		{

			@Override
			public void onRightItemSelect(int leftIndex, int rightIndex, Object leftModel, Object rightModel)
			{
				Quan_listQuan_subModel right = (Quan_listQuan_subModel) rightModel;
				quan_id = right.getId();
				mPtrlvContent.setRefreshing();
			}

			@Override
			public void onLeftItemSelect(int leftIndex, Object leftModel, boolean isNotifyDirect)
			{
				if (isNotifyDirect)
				{
					Quan_listModel left = (Quan_listModel) leftModel;
					Quan_listQuan_subModel right = left.getQuan_sub().get(0);
					quan_id = right.getId();
					mPtrlvContent.setRefreshing();
				}
			}
		});

		mCvRight.setmBackgroundNormal(R.drawable.bg_choosebar_press_down_3);
		mCvRight.setmBackgroundSelect(R.drawable.bg_choosebar_press_up_3);
		mCvRight.setmTextColorNormal(getResources().getColor(color.text_home_item_content));
		mCvRight.setmTextColorSelect(getResources().getColor(color.main_color));
		mCvRight.setmListener(new SDLvCategoryViewListener()
		{
			@Override
			public void onItemSelect(int index, Object model)
			{
				if (model instanceof CategoryOrderModel)
				{
					CategoryOrderModel orderModel = (CategoryOrderModel) model;
					order_type = orderModel.getValue();
					mPtrlvContent.setRefreshing();
				}
			}
		});

		List<CategoryOrderModel> listOrderModel = new ArrayList<CategoryOrderModel>();
		CategoryOrderModel orderModelDefault = new CategoryOrderModel();
		orderModelDefault.setName(CategoryOrderTypeName.DEFAULT);
		orderModelDefault.setValue(CategoryOrderTypeValue.DEFAULT);
		listOrderModel.add(orderModelDefault);

		CategoryOrderModel orderModelNearBy = new CategoryOrderModel();
		orderModelNearBy.setName(CategoryOrderTypeName.NEARBY);
		orderModelNearBy.setValue(CategoryOrderTypeValue.NEARBY);
		listOrderModel.add(orderModelNearBy);

		CategoryOrderModel orderModelPoint = new CategoryOrderModel();
		orderModelPoint.setName(CategoryOrderTypeName.AVG_POINT);
		orderModelPoint.setValue(CategoryOrderTypeValue.AVG_POINT);
		listOrderModel.add(orderModelPoint);

		CategoryOrderModel orderModelNewest = new CategoryOrderModel();
		orderModelNewest.setName(CategoryOrderTypeName.NEWEST);
		orderModelNewest.setValue(CategoryOrderTypeValue.NEWEST);
		listOrderModel.add(orderModelNewest);

		CategoryOrderModel orderModelBuyCount = new CategoryOrderModel();
		orderModelBuyCount.setName(CategoryOrderTypeName.BUY_COUNT);
		orderModelBuyCount.setValue(CategoryOrderTypeValue.BUY_COUNT);
		listOrderModel.add(orderModelBuyCount);

		CategoryOrderModel orderModelPriceAsc = new CategoryOrderModel();
		orderModelPriceAsc.setName(CategoryOrderTypeName.PRICE_ASC);
		orderModelPriceAsc.setValue(CategoryOrderTypeValue.PRICE_ASC);
		listOrderModel.add(orderModelPriceAsc);

		CategoryOrderModel orderModelPriceDesc = new CategoryOrderModel();
		orderModelPriceDesc.setName(CategoryOrderTypeName.PRICE_DESC);
		orderModelPriceDesc.setValue(CategoryOrderTypeValue.PRICE_DESC);
		listOrderModel.add(orderModelPriceDesc);

		CategoryOrderAdapter adapter = new CategoryOrderAdapter(listOrderModel, this);
		mCvRight.setAdapter(adapter);
	}

	private void requestData(final boolean isLoadMore)
	{
		RequestModel model = new RequestModel();
		model.put("act", "youhuilist");
		model.put("city_id", AppRuntimeWorker.getCity_id());
		model.put("quan_id", quan_id); // 商圈
		model.put("cate_id", cate_id);// 大分类ID
		model.put("merchant_id", merchant_id);// 大分类ID
		model.put("keyword", keyword);
		model.put("order_type", order_type); // 排序类型
		model.put("m_latitude", BaiduMapManager.getInstance().getLatitude());
		model.put("m_longitude", BaiduMapManager.getInstance().getLongitude());
		model.put("page", page);
		RequestCallBack<String> handler = new RequestCallBack<String>()
		{

			@Override
			public void onStart()
			{
				AppHelper.showLoadingDialog("请稍候...");
			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo)
			{
				YouhuilistActModel actModel = JsonUtil.json2Object(responseInfo.result, YouhuilistActModel.class);
				if (!SDInterfaceUtil.isActModelNull(actModel))
				{
					if (isFirstBindCategoryViewData)
					{
						bindLeftCategoryViewData(actModel.getBcate_list());
						bindMiddleCategoryViewData(actModel.getQuan_list());
						isFirstBindCategoryViewData = false;
					}

					if (actModel.getPage() != null)
					{
						page = actModel.getPage().getPage();
						pageTotal = actModel.getPage().getPage_total();
					}
					SDViewUtil.updateAdapterByList(mListModel, actModel.getItem(), mAdapter, isLoadMore);
				}
			}

			@Override
			public void onFailure(HttpException error, String msg)
			{

			}

			@Override
			public void onFinish()
			{
				dealFinishRequest();
			}
		};
		InterfaceServer.getInstance().requestInterface(model, handler);

	}

	protected void dealFinishRequest()
	{
		AppHelper.hideLoadingDialog();
		mPtrlvContent.onRefreshComplete();
		SDViewUtil.toggleEmptyMsgByList(mListModel, mLlEmpty);
	}

	private void bindLeftCategoryViewData(List<Bcate_listModel> listModel)
	{
		if (listModel != null && listModel.size() > 0)
		{
			Bcate_listModel leftModel = listModel.get(0);
			if (leftModel != null)
			{
				List<Bcate_listBcate_typeModel> listRight = leftModel.getBcate_type();

				CategoryCateLeftAdapter adapterLeft = new CategoryCateLeftAdapter(listModel, YouHuiListActivity.this);
				adapterLeft.setDefaultSelectId(cate_id);

				CategoryCateRightAdapter adapterRight = new CategoryCateRightAdapter(listRight, YouHuiListActivity.this);

				mCvLeft.setLeftAdapter(adapterLeft);
				mCvLeft.setRightAdapter(adapterRight);
				mCvLeft.setAdapterFinish();
			}
		}
	}

	private void bindMiddleCategoryViewData(List<Quan_listModel> listModel)
	{
		if (listModel != null && listModel.size() > 0)
		{
			Quan_listModel leftModel = listModel.get(0);
			if (leftModel != null)
			{
				List<Quan_listQuan_subModel> listRight = leftModel.getQuan_sub();

				CategoryQuanLeftAdapterNew adapterLeft = new CategoryQuanLeftAdapterNew(listModel, YouHuiListActivity.this);
				CategoryQuanRightAdapterNew adapterRight = new CategoryQuanRightAdapterNew(listRight, YouHuiListActivity.this);
				mCvMiddle.setLeftAdapter(adapterLeft);
				mCvMiddle.setRightAdapter(adapterRight);
				mCvMiddle.setAdapterFinish();
			}
		}
	}

	private void registeClick()
	{
		mIvLocation.setOnClickListener(this);
		mBtnYouhuiquan.setOnClickListener(this);
		mBtnDaijinquan.setOnClickListener(this);
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{

		case R.id.act_youhui_list_tv_location:
			clickTv_locaiton();
			break;
		case R.id.btn_daijinquan:
			mFLfrag_fl_youhui.setVisibility(View.VISIBLE);
			mPtrlvContent.setVisibility(View.GONE);
			mIv_daijinquan.setVisibility(View.VISIBLE);
			mIv_youhuiquan.setVisibility(View.INVISIBLE);
		break;
		case R.id.btn_youhuquan:
			mFLfrag_fl_youhui.setVisibility(View.GONE);
			mPtrlvContent.setVisibility(View.VISIBLE);
			mIv_daijinquan.setVisibility(View.INVISIBLE);
			mIv_youhuiquan.setVisibility(View.VISIBLE);
		break;

		default:
			break;
		}
	}

	private void clickTv_locaiton()
	{
		locationAddress();
	}

	/**
	 * 定位地址
	 */
	private void locationAddress()
	{
		// 开始定位
		mIvLocation.setVisibility(View.GONE);
		setCurrentLocationCity("定位中...", false);
		BaiduMapManager.getInstance().startLocation(new BDLocationListener()
		{
			@Override
			public void onReceivePoi(BDLocation arg0)
			{

			}

			@Override
			public void onReceiveLocation(BDLocation location)
			{

				if (location != null)
				{
					String strAddress = location.getAddrStr();
					if (!AppHelper.isEmptyString(strAddress) && strAddress.contains(Constant.EARN_SUB_CHAR))
					{
						strAddress = strAddress.substring(strAddress.indexOf(Constant.EARN_SUB_CHAR) + 1);
					}
					double lat = location.getLatitude();
					double lon = location.getLongitude();
					if (!TextUtils.isEmpty(strAddress) && lat > 0 && lon > 0)
					{
						setCurrentLocationCity(strAddress, true);
					}
				} else
				{
					setCurrentLocationCity("定位失败，点击重试", false);
				}
				// 定位回调完关闭，否则一直定位浪费电
				BaiduMapManager.getInstance().destoryLocation();
				mIvLocation.setVisibility(View.VISIBLE);
			}
		});
	}

	private void setCurrentLocationCity(String string, boolean isLocationSuccess)
	{
		if (!AppHelper.isEmptyString(string))
		{
			if (mTvAddress != null)
			{
				mTvAddress.setText(string);
				if (isLocationSuccess)
				{
					// 这个刷新有BUG会保留原始状态
					mPtrlvContent.setRefreshing();
				}
			}
		}
	}

	@Override
	public void onEventMainThread(SDBaseEvent event)
	{
		// TODO Auto-generated method stub
		super.onEventMainThread(event);
		switch (EnumEventTag.valueOf(event.getEventTagInt()))
		{
		case CITY_CHANGE:
			mPtrlvContent.setRefreshing();
			break;

		default:
			break;
		}
	}
}